package cfs.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import cfs.databean.Customer;
import cfs.databean.Employee;
import cfs.formbean.LoginForm;
import cfs.model.CustomerDAO;
import cfs.model.EmployerDAO;
import cfs.model.Model;

/**
 * Servlet implementation class LoginController
 */
public class LoginAction extends Action {

	private FormBeanFactory<LoginForm> formBeanFactory = FormBeanFactory
			.getInstance(LoginForm.class);
	CustomerDAO userDAO;
	EmployerDAO employeeDAO;

	/**
	 * @param model
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginAction(Model model) {
		super();
		userDAO = model.getCustomerDao();
		employeeDAO = model.getEmployerDao();
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "login.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		try {
			LoginForm form = formBeanFactory.create(request);
			request.setAttribute("form", form);

			if (!form.isPresent()) {
				return "login.jsp";
			}

			// Any validation errors?
			errors.addAll(form.getValidationErrors());
			if (errors.size() != 0) {
				return "login.jsp";
			}

			if (form.getType().equals("user")) {
				// Look up the user
				Customer user = userDAO.getCustomerByUserName(form
						.getUserName());

				if (user == null) {
					errors.add("User Name not found");
					return "login.jsp";

				}
				// Check the password
				if (!user.checkPassword(form.getPassword())) {
					errors.add("Incorrect password");
					return "login.jsp";

				}

				// Attach (this copy of) the user bean to the session
				HttpSession session = request.getSession();
				session.setAttribute("user", user);

				return Action.perform("viewAccount.do", request);
			} else if (form.getType().equals("employee")) {
				Employee emp = employeeDAO.lookup(form.getUserName());
				if (emp == null) {
					errors.add("Employee Name not found");
					return "login.jsp";
				}

				// check the password
				if (!emp.checkPassword(form.getPassword())) {
					errors.add("Incorrect password");
					return "login.jsp";
				}
				// Attach (this copy of) the employee bean to the session
				HttpSession session = request.getSession();
				session.setAttribute("employee", emp);

				return Action.perform("viewFundList.do", request);
			}

		} catch (FormBeanException e) {
			errors.add(e.getMessage());
			return "login.jsp";

		} catch (DAOException e) {
			errors.add(e.getMessage());
			return "login.jsp";
		}
		return "login.jsp";
	}
}
